package com.time.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.time.domain.Order;
import com.time.domain.OrderDetail;
import com.time.mapper.OrderDetailMapper;
import com.time.mapper.OrderMapper;
import com.time.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 周杰
 * @Description 订单service接口实现类
 * @since 2020-10-19
 */

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrder(Order order) {
        // 添加订单
        int addOrder = orderMapper.insert(order);
        int addOrderDetail = 0;

        // 添加订单详细数据
        for (OrderDetail orderDetail : order.getOrderDetails()) {
            orderDetail.setOId(order.getId());
            addOrderDetail = orderDetailMapper.insert(orderDetail);
        }

        return addOrder > 0 && addOrderDetail > 0;
    }

    @Override
    public Page<Order> orderByIdOrUserNamePage(Integer id, String userName, Page<Order> page) {
        LambdaQueryWrapper<Order> orderQuery = new LambdaQueryWrapper<>();
        orderQuery.like(id != null, Order::getId, "%" + id + "%")
                .like(StringUtils.isNoneBlank(userName), Order::getUserName, "%" + userName + "%");

        return orderMapper.selectPage(page, orderQuery);
    }
}
